package com.j180.servlet;

import com.j180.util.EncryptUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {


       //获得三个输入框的值
        String name = req.getParameter("userName");
        String pwd = req.getParameter("pwd");
        String keep = req.getParameter("Keep_record");

        Cookie[] cookies = req.getCookies();
        //判断是否有用户名和cookie时候存在，存在则需解码
        if(cookies!=null){

            for (Cookie cookie : cookies) {
                if(cookie.getName().equals("userName")){
                    name = EncryptUtil.Base64Decode(name);
                }else if(cookie.getName().equals("pwd")){
                    pwd = EncryptUtil.Base64Decode(pwd);
                }
            }
        }

        Cookie name_cookie = new Cookie("userName", EncryptUtil.Base64Encode(name));
        Cookie pwd_cookie = new Cookie("pwd",EncryptUtil.Base64Encode(pwd));

        if("abc".equals(name)&&"123".equals(pwd)){
              //判断是否勾选了3天免登录
              if(keep!=null){
                  name_cookie.setMaxAge(2*60);
                  pwd_cookie.setMaxAge(2*60);
                  resp.addCookie(name_cookie);
                  resp.addCookie(pwd_cookie);
              }else{
                  //让cookie失效
                  name_cookie.setMaxAge(0);
                  pwd_cookie.setMaxAge(0);
                  name_cookie.setPath("/");
                  pwd_cookie.setPath("/");
                  resp.addCookie(name_cookie);
                  resp.addCookie(pwd_cookie);
              }

              //创建一个session
            HttpSession session = req.getSession();
              //往session对象中存入数据
            session.setAttribute("isLogin","ok");
            session.setAttribute("num",100);
            //session默认有效期
            System.out.println(session.getMaxInactiveInterval());
            //设置session的有效期有三种
            //设置session的有效激活事件（发呆事件）
            //session.setMaxInactiveInterval(60*2);
            //立即失效(主要做完全登录的)
           // session.invalidate();


              //重定向
              //resp.sendRedirect("main.html");

            resp.sendRedirect("show");

          }else{
             // resp.sendRedirect("no.html");
              resp.sendRedirect("login.html");
          }


    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }
}
